import shlex
import json
import os # 导入 os 模块用于处理文件路径

def curl_to_requests(curl_command):
    """
    将 curl 命令字符串转换为 Python requests 库的代码。

    Args:
        curl_command (str): 要转换的 curl 命令字符串。

    Returns:
        str: 对应的 Python requests 代码。
    """
    lexer = shlex.shlex(curl_command, posix=True)
    lexer.whitespace_split = True
    lexer.escape = '' # 禁用转义，让 shlex 处理引号内的内容

    parts = list(lexer)

    method = 'GET'
    url = ''
    headers = {}
    data = {}

    i = 0
    while i < len(parts):
        part = parts[i]

        if part == 'curl':
            i += 1
            continue
        elif part in ('--location', '-L'):
            # --location 只是跟随重定向，requests 默认会处理
            i += 1
            continue
        elif part in ('--request', '-X'):
            method = parts[i+1].upper()
            i += 2
        elif part in ('--header', '-H'):
            header_str = parts[i+1]
            if ':' in header_str:
                key, value = header_str.split(':', 1)
                headers[key.strip()] = value.strip()
            i += 2
        elif part in ('--data', '--data-raw', '--data-ascii', '--data-urlencode', '-d'):
            data_str = parts[i+1]
            if '=' in data_str:
                key, value = data_str.split('=', 1)
                data[key.strip()] = value.strip()
            else:
                data = data_str
            i += 2
        elif part.startswith("http://") or part.startswith("https://"):
            url = part
            i += 1
        else:
            i += 1

    if isinstance(data, dict) and 'Content-Type' not in headers:
        pass
    elif isinstance(data, str) and 'Content-Type' not in headers and method != 'GET':
        headers['Content-Type'] = 'application/json' # 假设是json，如果不是需要手动调整


    # 构建 Python 代码字符串
    code = "import requests\n\n"
    code += f"url = '{url}'\n\n"

    if headers:
        headers_str = json.dumps(headers, indent=4, ensure_ascii=False)
        code += f"headers = {headers_str}\n\n"
    else:
        code += "headers = {}\n\n"

    if data:
        if isinstance(data, dict):
            data_str = json.dumps(data, indent=4, ensure_ascii=False)
            code += f"data = {data_str}\n\n"
        else: # assuming data is a string
            code += f"data = '''{data}'''\n\n"
    else:
        code += "data = {}\n\n"

    code += "try:\n"
    if method == 'GET':
        code += f"    response = requests.get(url, headers=headers)\n"
    elif method == 'POST':
        code += f"    response = requests.post(url, headers=headers, data=data)\n"
    elif method == 'PUT':
        code += f"    response = requests.put(url, headers=headers, data=data)\n"
    elif method == 'DELETE':
        code += f"    response = requests.delete(url, headers=headers, data=data)\n"
    else:
        code += f"    response = requests.request('{method}', url, headers=headers, data=data)\n"

    code += "    response.raise_for_status()  # 如果请求失败（例如，4xx 或 5xx 状态码），将引发异常\n"
    code += "    print('请求成功！')\n"
    code += "    print('状态码:', response.status_code)\n"
    code += "    print('响应内容:')\n"
    code += "    print(response.text)\n"
    code += "except requests.exceptions.RequestException as e:\n"
    code += "    print(f'请求失败: {e}')\n"

    return code